package com.jingdun.sport.files

import cn.hutool.core.date.DateUtil
import cn.hutool.core.io.FileUtil
import cn.hutool.core.util.IdUtil
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper
import com.jingdun.sport.common.bean.Qiniu
import com.jingdun.sport.common.util.Json
import com.losttemple.sql.language.dialects.DialectEnvironment
import com.losttemple.sql.language.operator.db
import com.qiniu.common.QiniuException
import com.qiniu.storage.BucketManager
import com.qiniu.storage.UploadManager
import com.qiniu.storage.model.DefaultPutRet
import com.qiniu.util.Auth
import com.qiniu.util.StringMap
import lombok.Data
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.*

@Service
class AttachFileServiceImpl {
    @Autowired
    private lateinit var uploadManager: UploadManager

    @Autowired
    private lateinit var qiniu: Qiniu

    @Autowired
    private lateinit var auth: Auth

    @Autowired
    private lateinit var sql: DialectEnvironment

    fun uploadFile(bytes: ByteArray, originalName: String?): String {
        val extName = FileUtil.extName(originalName)
        val fileName = DateUtil.format(Date(), NORM_MONTH_PATTERN) + IdUtil.simpleUUID() + "." + extName

        sql.run {
            db { Files(it) }.insert {
                it.path(fileName)
                it.size(bytes.size)
                it.type(extName)
                it.uploadTime(Date())
            }()
        }
        val upToken = auth.uploadToken(qiniu.bucket, fileName)
        val response = uploadManager.put(bytes, fileName, upToken)
        Json.parseObject(response.bodyString(), DefaultPutRet::class.java)
        return fileName
    }

    companion object {
        const val NORM_MONTH_PATTERN = "yyyy/MM/"
    }
}